/**
 * 
 */
package com.effectiv.req1.controller;


import javax.validation.Valid;

import jodd.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.effectiv.req1.business.api.ProjectService;
import com.effectiv.req1.business.api.UseCaseService;
import com.effectiv.req1.domain.Actor;

import com.effectiv.req1.domain.Project;

/**
 * @author Dhrubo
 * 
 */
@Controller
@Slf4j
public class ActorController {

	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private UseCaseService useCaseService;

	
	@RequestMapping(value = "/newactor")
	public final String newUserDisplay(@RequestParam(value = "usecase", required=false) String usecaseId,
			@RequestParam(value = "project") String projectId, Model model) {

		log.debug("Displaying UI to create new actor");

		Actor actor = new Actor();
		
		if(StringUtil.isNotEmpty(usecaseId)){
			model.addAttribute(useCaseService.findOne(usecaseId));
		}

		model.addAttribute(actor);
		model.addAttribute(projectService.findOne(projectId));

		return "newactor";
	}

	@RequestMapping(value = "/saveactor", method = RequestMethod.POST)
	public @ResponseBody AjaxResponse save(@Valid Actor actor,
			@RequestParam(value = "project") String projectId,
			BindingResult result, AjaxResponse response) {

		log.debug("Saving actor = {}", actor);
		log.debug("projectId = {}", projectId);

		if (!result.hasErrors()) {

			Project project = projectService.addActor(projectId, actor);			
			response.setResult(project);
		}
		else{
			response.markValidationFailure(result.getFieldErrors());
		}

		return response;
	}

}
